package modelType

import (
	"database/sql/driver"
	"fmt"
	"strconv"
	"strings"
)

// ArrayStringType 字符串数组
type ArrayStringType []string

func (receiver ArrayStringType) Value() (driver.Value, error) {
	if len(receiver) <= 0 {
		return nil, nil
	}
	str := strings.Join(receiver, ",")
	return str, nil
}

func (receiver *ArrayStringType) Scan(value interface{}) error {
	v := strings.Split(string(value.([]byte)), ",")
	var nv []string
	for _, s := range v {
		if s != "" {
			nv = append(nv, s)
		}
	}
	*receiver = nv
	return nil
}

// ArrayIntType 整形数组
type ArrayIntType []int

func (receiver ArrayIntType) Value() (driver.Value, error) {

	var newArray []string
	if len(receiver) <= 0 {
		return "", nil
	}
	for _, val := range receiver {
		newArray = append(newArray, strconv.Itoa(val))
	}
	newStr := strings.Join(newArray, ",")
	return newStr, nil
}

func (receiver *ArrayIntType) Scan(value interface{}) error {

	var newArray []int
	for _, s := range strings.Split(string(value.([]byte)), ",") {
		ns, _ := strconv.Atoi(s)
		newArray = append(newArray, ns)
	}
	*receiver = newArray

	return nil
}

// ArrayFloatType 浮点型数组 精度为3
type ArrayFloatType []float64

func (receiver ArrayFloatType) Value() (driver.Value, error) {
	var newArray []string
	if len(receiver) <= 0 {
		return "", nil
	}
	for _, val := range receiver {
		newArray = append(newArray, fmt.Sprintf("%.3f", val))
	}
	newStr := strings.Join(newArray, ",")
	return newStr, nil
}

func (receiver *ArrayFloatType) Scan(value interface{}) error {
	var newArray []float64
	for _, s := range strings.Split(string(value.([]byte)), ",") {
		ns, _ := strconv.ParseFloat(s, 3)
		newArray = append(newArray, ns)
	}
	*receiver = newArray
	return nil
}
